<template>
  <!-- 能耗计量设备 -->
  <div class="inspect">
    <lb-layout
      v-loading="$store.getters.loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="#a19f9fb0;"
      :paddBottom="5"
    >
      <el-row>
        <el-col :span="24" class="search-row">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
          >
            <el-form-item prop="sysDeptId">
              <cascader-select
                v-model="sysDeptIdArr"
                :values="sysDeptIdArr"
                size="small"
                varient="energy"
                placeholder="用能单位"
                @input="getsysDeptId"
              ></cascader-select>
            </el-form-item>
            <el-form-item prop="monitoringNetworkId">
              <RemoteSelect
                v-model="queryParams.monitoringNetworkId"
                varient="networks"
                size="small"
                :extraParams="extraParams"
                :propss="{
                  label: 'name',
                  value: 'id',
                }"
                placeholder="能耗终端"
                @input="handlegetNetwork"
              ></RemoteSelect>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="handleQuery"
              >
                搜索
              </el-button>
              <el-button
                icon="el-icon-refresh"
                size="small"
                @click="resetQuery"
              >
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-row class="mt10">
        <el-col :span="8">
          <pannel-Title name="报警统计">
            <img slot="icon" src="@/assets/images/inspect/report.png" alt="" />
            <el-button
              type="primary"
              slot="tips"
              size="small"
              @click="goWaring"
            >
              数据
            </el-button>
            <el-row class="informed" :gutter="10">
              <el-col :span="8">
                <div class="informed-item big">
                  <img
                    src="@/assets/images/inspect/inspectTotality.png"
                    alt=""
                  />
                  <p class="info-title">预警总数</p>
                  <p class="total">
                    <span :class="informed.totalAlarm > 0 ? 'red' : ''">
                      {{ informed.totalAlarm }}
                    </span>
                  </p>
                </div>
              </el-col>
              <el-col :span="16">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <div class="informed-item smalls">
                      <img
                        src="@/assets/images/inspect/inspectOffline.png"
                        alt=""
                      />
                      <div class="total">
                        <p class="info-title">应关未关</p>
                        <span :class="informed.notCloseNum > 0 ? 'red' : ''">
                          {{ informed.notCloseNum }}
                        </span>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="informed-item smalls">
                      <img
                        src="@/assets/images/inspect/inspectGateway.png"
                        alt=""
                      />
                      <div class="total">
                        <p class="info-title">离线率</p>
                        <span :class="informed.offlineRate > 0 ? 'red' : ''">
                          {{ informed.offlineRate.toFixed(2) }} </span
                        >%
                      </div>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="10" style="margin-top: 10px">
                  <el-col :span="12">
                    <div class="informed-item smalls">
                      <img
                        src="@/assets/images/inspect/inspectTelemetering.png"
                        alt=""
                      />
                      <div class="total">
                        <p class="info-title">
                          {{ activeName2 == "0" ? "过压过流" : "电量异常数" }}
                        </p>
                        <span
                          :class="
                            (activeName2 == '0' &&
                              informed.overVoltageAndOverCurrentNum > 0) ||
                            (activeName2 == '1' && informed.lowPowerNum > 0)
                              ? 'red'
                              : ''
                          "
                        >
                          {{
                            activeName2 == "0"
                              ? informed.overVoltageAndOverCurrentNum
                              : informed.lowPowerNum
                          }}
                        </span>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="12" v-show="activeName2 == '0'">
                    <div class="informed-item smalls">
                      <img
                        src="@/assets/images/inspect/inspectCommunication.png"
                        alt=""
                      />
                      <div class="total">
                        <p class="info-title">恶性负载</p>
                        <span :class="informed.overloadNum > 0 ? 'red' : ''">
                          {{ informed.overloadNum }}
                        </span>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </pannel-Title>
        </el-col>
        <el-col :span="11" v-show="activeName2 == '0'">
          <pannel-Title name="实时负荷" style="margin: 0 10px">
            <img slot="icon" src="@/assets/images/inspect/load.png" alt="" />
            <el-button
              type="primary"
              slot="tips"
              size="small"
              @click="showModel('loadTable')"
              >数据
            </el-button>
            <lineChart :lineData="dataArr" :xData="xData" :mapData="mapData" />
          </pannel-Title>
        </el-col>
        <el-col :span="5" v-show="activeName2 == '0'">
          <pannel-Title name="漏电监测">
            <img slot="icon" src="@/assets/images/inspect/leakage.png" alt="" />
            <el-button
              type="primary"
              slot="tips"
              size="small"
              @click="showModel('leakageTable')"
              >数据
            </el-button>
            <div class="leakage">
              <div class="leakage-item">
                <img src="@/assets/images/inspect/leakage1.png" alt="" />
                <div class="leakage-item-right">
                  <div class="lir-num">
                    <span>{{ leakageAll.summaryEnergyConsumptionAll }}</span>
                    <span>kwh</span>
                  </div>
                  <div class="lir-title">
                    <span>总能耗</span>
                  </div>
                </div>
              </div>
              <div class="leakage-item">
                <img src="@/assets/images/inspect/leakage2.png" alt="" />
                <div class="leakage-item-right">
                  <div class="lir-num">
                    <span>{{ leakageAll.branchEnergyConsumptionAll }}</span>
                    <span>kwh</span>
                  </div>
                  <div class="lir-title">
                    <span>支路总能耗</span>
                  </div>
                </div>
              </div>
            </div>
          </pannel-Title>
        </el-col>
        <el-col :span="16" v-show="activeName2 == '1'">
          <pannel-Title name="水耗负载分析" style="margin-left: 10px">
            <img slot="icon" src="@/assets/images/inspect/load-2.png" alt="" />
            <el-button type="primary" slot="tips" size="small" @click="goEnergy"
              >数据
            </el-button>
            <waterChart
              :lineData="waterdataArr"
              :xData="waterxData"
              :mapData="watermapData"
            />
          </pannel-Title>
        </el-col>
      </el-row>
      <list
        v-if="activeName2 == '0'"
        :datas="datas"
        :totalalarmNum="totalalarmNum"
      ></list>
      <waterlist
        v-if="activeName2 == '1'"
        :datas="waterdatas"
        :totalwateralarmNum="totalwateralarmNum"
      ></waterlist>
      <component
        :is="modelName"
        :id="id"
        :leakageChartdata="leakageChartdata"
        :visible.sync="show"
        @close="close"
      ></component>
      <alarmCom
        class="alarmCom-area"
        ref="alarmCom"
        :arr="alarmArr"
        @closeAlarm="closeAlarm"
      ></alarmCom>

    </lb-layout>
  </div>
</template>

<script>
import lineChart from "@/views/maintenance/realtime/inspect/components/lineChart.vue";
import waterChart from "@/views/maintenance/realtime/inspect/components/waterChart.vue";
import list from "@/views/maintenance/realtime/inspect/components/list.vue";
import waterlist from "@/views/maintenance/realtime/inspect/components/waterlist.vue";
import loadTable from "@/views/maintenance/realtime/inspect/components/loadTable.vue";
import leakageTable from "@/views/maintenance/realtime/inspect/components/leakageTable.vue";
import alarmCom from "@/views/maintenance/realtime/inspect/components/alarm.vue";
import CascaderSelect from "@/components/Select/CascaderSelect"; // 下拉多级联选
import RemoteSelect from "@/components/Select/RemoteSelect"; // 远程下拉
import {
  loadList,
  newGraphlist,
  newAlarm,
  newWateralarm,
  waterLine,
  postwaterList,
  postPingpong,
  postTotal,
  postTotalwater,
  geGraphtodayList,
} from "@/api/iot/inspect";
import { getnetworks } from "@/api/system/dept";
import { dealElectricity, deepClone } from "@/utils/index";

export default {
  name: "inspect",
  components: {
    lineChart,
    waterChart,
    list,
    waterlist,
    loadTable,
    leakageTable,
    CascaderSelect,
    RemoteSelect,
    alarmCom,
  },
  dicts: ["sys_normal_disable", "device_status", "subentry_type"],
  data() {
    return {
      // tab
      activeName: "1",
      activeName2: "0",
      // tabArr: [
      //   {
      //     label: "计量电表",
      //     value: "0",
      //   },
      //   {
      //     label: "计量水表",
      //     value: "1",
      //   },
      // ],
      // 电表分项列表
      datas: {
        list: [],
        total: 0,
        allelectricCurrent: 0,
        allpower: 0,
        averagevoltage: 0,
      },
      // 水表分项列表
      waterdatas: {
        list: [],
        total: 0,
        totalWater: 0, // 累计水耗
        caliber40: 0, // 40口径数量
        caliber50: 0, // 50口径数量
      },
      id: "",
      modelName: "",
      show: false,
      queryParams: {
        sysDeptId: null,
        monitoringNetworkId: null,
      },
      extraParams: {},
      sysDeptIdArr: [],
      // 报警统计
      informed: {
        totalAlarm: 0, // 警报数量
        notCloseNum: 0, // 应关未关
        offlineRate: 0, // 离线率
        overloadNum: 0, // 恶性负载
        overVoltageAndOverCurrentNum: 0, // 过压过流数量
        lowPowerNum: 0, // 低电压数量
      },
      xData: [],
      dataArr: [],
      mapData: [],
      waterxData: [],
      waterdataArr: [], // 水表趋势分析表数据
      watermapData: [],
      timmer: null,
      alarmArr: [], // 报警数据
      alarmContinueId: null,
      alarmClosetime: 300000, // 报警弹框关闭时间(5min)
      totalalarmNum: {
        totalNum: 0,
        highFrequencyAlarmNum: 0,
        noAlarmNum: 0,
        lowFrequencyAlarmNum: 0,
      }, // 电表警报小计
      totalwateralarmNum: {
        totalNum: 0,
        highFrequencyAlarmNum: 0,
        noAlarmNum: 0,
        lowFrequencyAlarmNum: 0,
      }, // 水表警报小计
      showAlarm: false,
      leakageAll: {
        summaryEnergyConsumptionAll: 0, // 总能耗 （保留两位小数）
        branchEnergyConsumptionAll: 0, // 支路总能耗（保留两位小数）
      },
      leakageChartdata: {
        legendData: ["总能耗", "支路总能耗"],
        color: ["#5C9CD5", "#10B767", "#ED7D31", "#A5A5A5", "#FFC000"],
        xAxisData: [],
        seriesData: [
          {
            name: "总能耗",
            type: "line",
            // yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          },
          {
            name: "支路总能耗",
            type: "line",
            // yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          },
          // {
          //   name: "",
          //   type: "bar",
          //   stack: "add",
          //   tooltip: {
          //     valueFormatter: function (value) {
          //       return value + "";
          //     },
          //   },
          //   data: [0],
          // },
        ],
      },
    };
  },
  created() {},
  mounted() {
    this.routerJudge();
    this.getmonitoringNetworkId();
    this.alarmRequest();
    this.timmer = setInterval(() => {
      // console.log(11);
      this.alarmRequest();
    }, 61000);
    this.$once("hook:beforeDestroy", () => {
      // console.log(22);
      clearInterval(this.timmer);
      this.timmer = null;
    });
  },
  // beforeDestroy() {
  //   clearInterval(this.timmer);
  //   this.timmer = null;
  // },
  methods: {
    routerJudge() {
      let routeflage = this.$route.path;
      // console.log(routeflage, "routeflage");
      switch (routeflage) {
        case "/maintenance/realtime/inspect":
          this.activeName2 = "0";
          break;
        case "/maintenance/realtime/inspect2":
          this.activeName2 = "1";
          break;
      }
    },
    closeAlarm(idflag) {
      this.alarmArr.map((item, index) => {
        if (this.alarmArr[index].id == idflag) {
          this.alarmArr.splice(index, 1);
        }
      });
    },
    // 设备当日线路损耗图形接口
    geGraphtodayListRequest() {
      let params = {};
      params.sysDeptId = this.queryParams.sysDeptId ?? null;
      params.monitoringNetworkId = this.queryParams.monitoringNetworkId ?? null;
      geGraphtodayList(params)
        .then((res) => {
          console.log(res, "漏电监测");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            this.leakageDatadeal(deepClone(arr));
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20000992");
        });
    },
    leakageDatadeal(arr) {
      let typeArr = this.dict?.type?.subentry_type ?? [];
      // 记录出现的分项种类
      let subentryTypeArr = [];
      let nameArr = [];
      arr.map((item) => {
        this.leakageAll.summaryEnergyConsumptionAll +=
          item?.summaryEnergyConsumption ?? 0;
        this.leakageAll.branchEnergyConsumptionAll +=
          item?.branchEnergyConsumption ?? 0;
        // 柱状图每条总能耗
        this.leakageChartdata.seriesData[0].data.push(
          dealElectricity(item?.summaryEnergyConsumption ?? 0, 100, 2)
        );
        // 柱状图每条支路总能耗
        this.leakageChartdata.seriesData[1].data.push(
          dealElectricity(item?.branchEnergyConsumption ?? 0, 100, 2)
        );
        // 柱状图X轴
        this.leakageChartdata.xAxisData.push(item?.dateTime ?? "");
        // bar数据整理
        let slist = item?.subentryTypeConsumptionBOList ?? [];
        if (slist.length > 0) {
          slist.map((pig) => {
            typeArr.map((tig) => {
              if (pig.subentryType == tig.value) {
                pig.name = tig.label;
              }
            });
            if (subentryTypeArr.length == 0) {
              subentryTypeArr.push(pig.subentryType);
              nameArr.push(pig.name);
            } else {
              if (subentryTypeArr.indexOf(pig.subentryType) == -1) {
                subentryTypeArr.push(pig.subentryType);
                nameArr.push(pig.name);
              }
            }
          });
        }
      });
      // 外层统计类
      this.leakageAll.summaryEnergyConsumptionAll = dealElectricity(
        this.leakageAll.summaryEnergyConsumptionAll,
        100,
        2
      );
      this.leakageAll.branchEnergyConsumptionAll = dealElectricity(
        this.leakageAll.branchEnergyConsumptionAll,
        100,
        2
      );
      // 添加bar
      if (subentryTypeArr.length > 0) {
        subentryTypeArr.map((sig, sigindex) => {
          this.leakageChartdata.legendData.push(nameArr[sigindex]);
          let obj = {
            name: nameArr[sigindex],
            subentryType: sig,
            type: "bar",
            stack: "add",
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          };
          this.leakageChartdata.seriesData.push(obj);
        });
      }
      // bar 的data数据传入
      arr.map((item) => {
        let slist2 = item?.subentryTypeConsumptionBOList ?? [];
        let slist2Length = slist2.length;
        this.leakageChartdata.seriesData.map((mig) => {
          mig.hasValue = false;
          let num = 0;
          if (slist2Length > 0) {
            slist2.map((tig) => {
              if (mig.subentryType == tig.subentryType) {
                mig.data.push(
                  dealElectricity(tig?.energyConsumption ?? 0, 100, 2)
                );
                mig.hasValue = true;
              } else {
                num++;
              }
            });
            if (num == slist2Length) {
              if (!mig.hasValue) {
                mig.data.push(dealElectricity(0, 100, 2));
                mig.hasValue = true;
              }
            }
          } else {
            if (!mig.hasValue) {
              mig.data.push(dealElectricity(0, 100, 2));
              mig.hasValue = true;
            }
          }
        });
      });
      console.log(this.leakageChartdata, "leakageChartdata");
    },
    // 获取电表警报小计信息
    totalRequest() {
      let params = {};
      params.sysDeptId = this.queryParams.sysDeptId ?? null;
      params.monitoringNetworkId = this.queryParams.monitoringNetworkId ?? null;
      postTotal(params)
        .then((res) => {
          // console.log(res, "警报小计信息");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.totalalarmNum.totalNum = res?.data?.totalNum ?? 0;
          this.totalalarmNum.highFrequencyAlarmNum =
            res?.data?.highFrequencyAlarmNum ?? 0;
          this.totalalarmNum.noAlarmNum = res?.data?.noAlarmNum ?? 0;
          this.totalalarmNum.lowFrequencyAlarmNum =
            res?.data?.lowFrequencyAlarmNum ?? 0;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!200098");
        });
    },
    //获取水表警报小计信息
    totalwaterRequest() {
      let params = {};
      params.sysDeptId = this.queryParams.sysDeptId ?? null;
      params.monitoringNetworkId = this.queryParams.monitoringNetworkId ?? null;
      postTotalwater(params)
        .then((res) => {
          // console.log(res, "water警报小计信息");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.totalwateralarmNum.totalNum = res?.data?.totalNum ?? 0;
          this.totalwateralarmNum.highFrequencyAlarmNum =
            res?.data?.highFrequencyAlarmNum ?? 0;
          this.totalwateralarmNum.noAlarmNum = res?.data?.noAlarmNum ?? 0;
          this.totalwateralarmNum.lowFrequencyAlarmNum =
            res?.data?.lowFrequencyAlarmNum ?? 0;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!200097");
        });
    },
    //  实时报警轮询
    alarmRequest() {
      //device_alarm_type
      let that = this;
      let params = {};
      console.log(this.alarmContinueId, "alarmContinueId");
      if (this.alarmContinueId) {
        params.id = this.alarmContinueId ?? null;
      }
      postPingpong(params)
        .then((res) => {
          if (res.code === 700) {
            if (res.msg != "访问过于频繁，请稍候再试") {
              this.$message.warning(res.msg);
            }
            return false;
          }
          let arr = res?.data ?? [];
          // console.log(arr, "新的报警数组");
          let lg = arr.length;
          if (lg > 0) {
            arr.map((item) => {
              let obj = {
                id: item.id,
                name1: item?.deptName ?? "",
                name2: item?.monitoringName ?? "",
                name3: item?.deviceCode ?? "",
                type: item?.alarmType,
                time: item?.eventTime ?? "",
                closeTime: Date.now() + that.alarmClosetime, // 自动关闭时间(5min)
              };
              // 一个计量电表一个预警类型展示一个弹窗（同ID）,5分钟内只更新时间
              if (this.alarmArr.length == 0) {
                this.alarmArr.push(obj);
              } else {
                let num = 0;
                this.alarmArr.map((pig) => {
                  if (pig.id == obj.id) {
                    pig.time = obj.time;
                    pig.closeTime = Date.now() + that.alarmClosetime;
                    num++;
                  }
                });
                if (num == 0) {
                  this.alarmArr.push(obj);
                }
              }
            });
            // // console.log(this.alarmArr, "报警信息");
            // setTimeout(() => {
            //   // this.$notify.close();
            //   this.$notify.error({
            //     title: "设备预警",
            //     dangerouslyUseHTMLString: true,
            //     message: (
            //       <alarmCom ref="alarmCom" arr={that.alarmArr}></alarmCom>
            //     ),
            //     position: "bottom-right",
            //     duration: 5000, // 5min自动关闭
            //     onClose() {
            //       that.alarmArr = [];
            //       // console.log(that.alarmArr, "报警信息");
            //     },
            //   });
            // }, 100);
          }
          let bg = this.alarmArr.length;
          if (bg > 0) {
            this.alarmContinueId = this.alarmArr[bg - 1]?.id ?? null;
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!200099");
        });
    },
    /* 默认选择用能单位最下级 */
    getmonitoringNetworkId() {
      // this.$store.commit("app/updateApiCount", "add");
      getnetworks()
        .then((res) => {
          // this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res.rows;
          // this.queryParams.monitoringNetworkId = arr[0].id;
          this.allRequest();
        })
        .catch((err) => {
          // this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20001");
        });
    },
    /* 默认请求集合 */
    allRequest() {
      if (this.activeName2 == "0") {
        this.getBudgetdata();
        this.postGraphlist();
        this.postAlarm();
        this.totalRequest();
        this.geGraphtodayListRequest();
      } else if (this.activeName2 == "1") {
        this.getWaterdata();
        this.postWaterlist();
        this.postAlarmwater();
        this.totalwaterRequest();
      }
    },
    /* 获取用能单位ID */
    getsysDeptId(value) {
      this.queryParams.monitoringNetworkId = null;
      this.queryParams.sysDeptId = value[value.length - 1];
      this.extraParams = {
        sysDeptId: this.queryParams.sysDeptId,
      };
    },
    /* 获取能耗终端ID */
    handlegetNetwork(value) {
      this.queryParams.monitoringNetworkId = value;
    },
    showModel(name, id) {
      this.modelName = name;
      if (this.modelName === "loadTable") {
        this.id = this.queryParams;
      } else {
        this.id = id || "";
      }
      this.show = true;
    },
    /* 跳转预警模型页面 */
    goWaring() {
      this.$router.push("/work/forewarningModel/alarmCommand").catch(() => {});
    },
    close(status) {
      this.show = false;
      if (status) {
        console.log("弹出层关闭需要重新加载数据");
      } else {
        console.log("弹出层关闭不需要重新加载数据");
      }
    },
    tabChange(type) {
      if (type == 1) {
        console.log(this.activeName);
        this.allRequest();
      } else if (type == 2) {
        console.log(this.activeName2);
        this.handleQuery();
      }
    },
    //....................................点击请求.................................
    /* 请求电表实时负荷 */
    getBudgetdata() {
      let params = this.queryParams;
      this.$store.commit("app/updateApiCount", "add");
      loadList(params)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // console.log(res, "实时负荷");
          let arr = res?.data?.realTimeLoadVoList ?? [];
          let brr = res?.data?.realTimeSectionListVo ?? [];
          this.dealBudgetdata(arr, brr);
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20003");
        });
    },
    dealBudgetdata(arr, brr) {
      this.dataArr = [];
      this.xData = [];
      this.mapData = [];
      if (arr.length === 0) {
        this.xData = ["时刻"];
        this.dataArr = [0];
      } else {
        arr.map((item) => {
          this.xData.push(item?.timeStr ?? "时刻");
          this.dataArr.push(Number(dealElectricity(item?.p ?? 0, 1000, 3)));
        });
      }
      let colorArr = [
        "#93CE07",
        "#FBDB0F",
        "#FC7D02",
        "#FD0100",
        "#AA069F",
        "#AC3B2A",
      ];
      if (brr.length === 0) {
        this.mapData = [
          {
            gt: 0,
            lte: 1,
            color: "#000000",
          },
        ];
      } else {
        brr.map((item, index) => {
          let obj = {
            gt: Number(dealElectricity(brr[index]?.gt ?? 0, 1000, 3)),
            lte: Number(dealElectricity(brr[index]?.lt ?? 1, 1000, 3)),
            color: colorArr[index],
          };
          this.mapData.push(obj);
        });
      }
    },
    /* 请求电设备列表*/
    postGraphlist() {
      let params = this.queryParams;
      newGraphlist(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // console.log(res, "list1");
          this.datas.list = res?.rows ?? [];
          if (this.datas.list.length > 0) {
            this.datas.list.map((item) => {
              let park = item?.park ?? "未知园区 ";
              let building = item?.building ?? "未知楼栋 ";
              let floor = item?.floor ?? "未知楼层 ";
              let room = item?.room ?? "未知房间号 ";
              item.realLocal = park + building + floor + room;
            });
          }
          this.datas.total = res?.total ?? 0;
          if (res.rows != null && res.rows.length > 0) {
            let e = 0;
            let p = 0;
            let v = 0;
            res.rows.map((item) => {
              e += item.electricCurrent;
              p += item.power;
              v += item.voltage;
            });
            v = v / res.rows.length;
            this.datas.allelectricCurrent = dealElectricity(e, 1000, 3);
            this.datas.allpower = dealElectricity(p, 1000, 3);
            this.datas.averagevoltage = dealElectricity(v);
          } else {
            this.datas.allelectricCurrent = 0;
            this.datas.allpower = 0;
            this.datas.averagevoltage = 0;
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20005");
        });
    },
    /* 请求最新报警统计-电表 */
    postAlarm() {
      let params = this.queryParams;
      newAlarm(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.informed.totalAlarm = res?.data?.totalAlarm ?? 0; // 预警总数
          this.informed.notCloseNum = res?.data?.notCloseNum ?? 0; // 应关未关
          this.informed.offlineRate = res?.data?.offlineRate ?? 0; // 离线率
          this.informed.overloadNum = res?.data?.overloadNum ?? 0; // 恶性负载
          this.informed.overVoltageAndOverCurrentNum =
            res?.data?.overVoltageAndOverCurrentNum ?? 0; // 过压过流数量
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20007");
        });
    },
    /* 请求最新报警统计-水表 */
    postAlarmwater() {
      let params = this.queryParams;
      newWateralarm(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.informed.totalAlarm = res?.data?.totalAlarm ?? 0; // 预警总数
          this.informed.notCloseNum = res?.data?.notCloseNum ?? 0; // 应关未关
          this.informed.offlineRate = res?.data?.offlineRate ?? 0; // 离线率
          this.informed.lowPowerNum = res?.data?.lowPowerNum ?? 0; // 电量异常数
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!200071");
        });
    },
    /* 请求水耗负载分析 */
    getWaterdata() {
      let params = this.queryParams;
      this.$store.commit("app/updateApiCount", "add");
      waterLine(params)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // console.log(res, "water");
          let arr = res?.data?.wmeterRealTimeLoadVoList ?? [];
          let brr = res?.data?.realTimeSectionVoList ?? [];
          this.dealWaterdata(arr, brr);
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20009");
        });
    },
    dealWaterdata(arr, brr) {
      this.waterxData = [];
      this.waterdataArr = [];
      this.watermapData = [];
      if (arr.length > 0) {
        arr.map((item) => {
          this.waterxData.push(item?.dateStr ?? "日期");
          this.waterdataArr.push(
            Number(dealElectricity(item?.waterConsumption ?? 0, 1000, 3))
          );
        });
      } else {
        this.waterxData = ["日期"];
        this.waterdataArr = [0];
      }
      let colorArr = [
        "#93CE07",
        "#FBDB0F",
        "#FC7D02",
        "#FD0100",
        "#AA069F",
        "#AC3B2A",
      ];
      if (brr.length === 0) {
        this.watermapData = [
          {
            gt: 0,
            lte: 1,
            color: "#000000",
          },
        ];
      } else {
        brr.map((item, index) => {
          let obj = {
            gt: Number(dealElectricity(brr[index]?.gt ?? 0, 1000, 3)),
            lte: Number(dealElectricity(brr[index]?.lt ?? 1, 1000, 3)),
            color: colorArr[index],
          };
          this.watermapData.push(obj);
        });
      }
    },
    /* 请求电水设备列表*/
    postWaterlist() {
      let params = this.queryParams;
      postwaterList(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // console.log(res, "list2");
          this.waterdatas.list = res?.rows ?? [];
          if (this.waterdatas.list.length > 0) {
            this.waterdatas.list.map((item) => {
              let park = item?.park ?? "未知园区 ";
              let building = item?.building ?? "未知楼栋 ";
              let floor = item?.floor ?? "未知楼层 ";
              let room = item?.room ?? "未知房间号 ";
              item.realLocal = park + building + floor + room;
            });
          }
          this.waterdatas.total = res?.total ?? 0;
          if (this.waterdatas.list.length > 0) {
            this.waterdatas.list.map((item) => {
              this.waterdatas.totalWater += item?.deviceTotalData ?? 0;
              if (item.caliber === 40) {
                this.waterdatas.caliber40++;
              }
              if (item.caliber === 50) {
                this.waterdatas.caliber50++;
              }
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20008");
        });
    },
    resetData() {
      this.informed = {
        totalAlarm: 0, // 警报数量
        notCloseNum: 0, // 应关未关
        offlineRate: 0, // 离线率
        overloadNum: 0, // 恶性负载
        overVoltageAndOverCurrentNum: 0, // 过压过流数量
        lowPowerNum: 0, // 低电压数量
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.resetData();
      if (this.activeName2 == "0") {
        // 获取实时负荷数据
        this.getBudgetdata();
        // 请求电设备列表
        this.postGraphlist();
        // 请求最新警报信息-电
        this.postAlarm();
        this.totalRequest();
      } else if (this.activeName2 == "1") {
        // 水耗负载分析
        this.getWaterdata();
        // 水表分项列表
        this.postWaterlist();
        // 请求最新警报信息-水
        this.postAlarmwater();
        this.totalwaterRequest();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.sysDeptIdArr = [];
      this.dateRange = [];
      this.resetForm("queryForm");
      this.getmonitoringNetworkId();
      this.$nextTick(() => {
        this.handleQuery();
      });
    },
    goEnergy() {
      let query = {
        tab: "1",
      };
      this.$router.push({ path: "/statistics/behavior/extremum", query: query }).catch(() => {});
    },
  },
};
</script>

<style scoped lang="scss">
.inspect {
  width: 100%;
  position: relative;
  padding-top: 0;
  .alarmCom-area {
    position: absolute;
    bottom: 5px;
    right: 5px;
  }
}
::v-deep .text-tabs {
  .el-tabs__active-bar {
    width: 79px;
  }
  .el-tabs__item {
    font-size: 20px;
    font-weight: 600;
    opacity: 0.8;
  }
}
.text-tabs {
  margin: 0 0 0 -30px;
}
.text-tabs-ex {
  margin: -10px 0 10px -40px;
}
.search-row {
  width: 100%;
  height: 30px;
}
.informed {
  .total {
    padding: 2px 0;
    margin: 0;
    span {
      font-size: 20px;
      color: #3595c8;
    }
    .red {
      color: #ff8194;
    }
  }
  .info-title {
    padding: 0;
    margin: 0;
    font-size: 16px;
  }
  .smalls {
    height: 105px;
    background: #f3f9fe;
    display: flex;
    img {
      width: 40px;
      height: 40px;
      margin: 0 6px;
    }
  }
  .big {
    height: 220px;
    text-align: center;
    img {
      width: 100px;
      height: 100px;
      margin: 0 20px;
    }
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .info-title {
      margin: 16px 0;
    }
  }
  .informed-item {
    overflow: hidden;
    border-radius: 10px;
    padding: 20px 0;
    // cursor: pointer;
    display: flex;
    align-items: center;
  }
  .informed-item-ex {
    height: 100px;
    margin-top: 10px;
    background: #f3f9fe;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    .tit {
      color: #3385ff;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-wrap: wrap;
      div {
        width: 50%;
        text-align: center;
        padding: 5px 0;
      }
    }
  }

  .p0 {
    padding-top: 0;
  }
}
.leakage {
  font-size: 14px;
  height: 220px;
  text-align: center;
  background: #fff;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: space-around;
  img {
    width: 50px;
    height: 50px;
  }
  .leakage-item {
    width: 100%;
    padding: 10px;
    background: #f3f9fe;
    border-radius: 8px;
    display: flex;
    align-items: center;
    .leakage-item-right {
      height: 50px;
      margin-left: 5px;
      text-align: left;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .lir-num {
        span {
          font-family: PingFangSC-Medium, PingFang SC;
          color: #3298f2;
          &:nth-child(1) {
            font-size: 16px;
            font-weight: 600;
            line-height: 20px;
          }
          &:nth-child(2) {
            font-size: 14px;
            font-weight: 400;
            line-height: 18px;
          }
        }
      }
      .lir-title {
        span {
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: rgba(34, 34, 34, 0.85);
          line-height: 20px;
        }
      }
    }
  }
}
.m10 {
  margin: 10px 0;
}
</style>
